package cmd

import (
	"os"
	"os/signal"
	"syscall"
	"time"

	"gitee.com/JMArch/service_addr_syncer/internal"
	"github.com/spf13/cobra"
	"github.com/zeast/logs"
)

var etcdEndpoints []string
var doveEnv string
var syncEtcdEndpoints []string
var logFile string
var syncDelDelay int

var StartCmd = &cobra.Command{
	Use:   "start",
	Short: "sync service info to dove key",
	PersistentPreRun: func(cmd *cobra.Command, args []string) {
		logs.LogFuncCall(true)
	},

	Run: func(cmd *cobra.Command, args []string) {
		w, err := logs.NewFileWriter(logs.FileConfig{
			Name: logFile,
			Rotate: &logs.Rotate{
				MaxSize: 1024 * 1024 * 1024,
				Daily:   true,
				MaxDays: 10,
			},
		})
		if err != nil {
			logs.Fatal(err)
		}

		logs.SetBaseWriter(w)
		logs.LogFuncCall(true)

		etcdSyncer, err := internal.NewEtcdSyncer(syncEtcdEndpoints, "lark.backup_address.", time.Duration(syncDelDelay)*time.Second)
		if err != nil {
			logs.Errorf("new etcd syncer: %s", err.Error())
		}

		syncer := internal.NewServiceSyncer()
		etcdCli, err := internal.NewEtcdCli(internal.EtcdCliConf{
			Endpoints:      etcdEndpoints,
			DelSerCallback: syncer.DelSer,
			PutSerCallback: syncer.PutSer,
			SetSerCallback: syncer.SetSer,
		}, etcdSyncer)
		if err != nil {
			logs.Fatal(err)
		}
		go etcdCli.Watch()

		doveCli, err := internal.NewDoveClient(internal.DoveClientConf{
			Env:      doveEnv,
			Username: "service_addr_syncer",
			Secret:   "service_addr_syncer",
			MapKey:   "RpcPool.ServiceName2DoveKey",
			Callback: syncer.SetDoveMap,
		})
		if err != nil {
			logs.Fatal(err)
		}

		if err := doveCli.Watch(); err != nil {
			logs.Fatal(err)
		}

		doveCli.WatchKey("RpcPool.UseBackup", etcdCli.WatchUseBackup)

		syncer.SetDoveCli(doveCli)

		sc := make(chan os.Signal, 1)
		signal.Notify(sc, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM)
		for sig := range sc {
			logs.Debugf("receive signal:%s, exit", sig.String())
			break
		}
	},
}
